package com.echoesnet.echoesshortvideo.Utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.ExifInterface;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.echoesnet.echoesshortvideo.Activities.CommonImageViewAct;
import com.echoesnet.echoesshortvideo.Activities.LoginAct;
import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Beans.ShareToFaceBean;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.R;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Copyright (C) 2018 科技发展有限公司
 * 完全享有此软件的著作权，违者必究
 *
 * @author ben
 * @version 1.0
 * @modifier
 * @createDate 2018/4/19 20:01
 * @description
 */
public class CommonUtils
{
    private static final String TAG = CommonUtils.class.getSimpleName();

    /**
     * 获得进程名称
     */
    public static String getProcessName(Context cxt, int pid)
    {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null)
        {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps)
        {
            if (procInfo.pid == pid)
            {
                return procInfo.processName;
            }
        }
        return null;
    }

    public static String getDeviceId()
    {
        String id = "";
        try
        {
            id = Settings.Secure.getString(AppController.getInstance().getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return id;
    }

    /**
     * dp转px
     *
     * @param context
     * @param dp
     * @return
     */
    public static int dp2px(Context context, float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dp,
                context.getResources().getDisplayMetrics());
    }

    /**
     * 得到设备屏幕的高度
     */
    public static int getScreenHeight(Context context)
    {
        if (context == null)
            context = AppController.getInstance();
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 得到设备屏幕的宽度
     */
    public static int getScreenWidth(Context context)
    {
        if (context == null)
            context = AppController.getInstance();
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 将字符串list拼接成含有分割付的串
     *
     * @param list
     * @param separator
     * @return
     */
    public static String listToStrWishSeparator(List<String> list, String separator)
    {
        if (list == null || list.size() == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++)
        {
            sb.append(list.get(i)).append(separator);
        }
        return sb.toString().substring(0, sb.toString().length() - separator.length());
    }



    /**
     * 跳转 查看大图
     *
     * @param context
     * @param urls            图片url集合
     * @param currentPosition 跳转目标position
     * @param view            控件点击的view
     */
    public static void showImageBrowser(Context context, List<String> urls, int currentPosition, View view)
    {

        Intent intent = new Intent(context, CommonImageViewAct.class);
        intent.putStringArrayListExtra(CommonConstant.EAM_SHOW_IMG_URLS, (ArrayList<String>) urls);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_CURRENT_ITEM, currentPosition);
        int[] location = new int[2];
        int width = 50;
        int height = 50;
        if (view == null)
        {
            location[0] = CommonUtils.getScreenWidth(context) / 2;
            location[1] = CommonUtils.getScreenHeight(context) / 2;
        }
        else
        {
            view.getLocationOnScreen(location);
            width = view.getWidth();
            height = view.getHeight();
        }
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_LOCATION_X, location[0]);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_LOCATION_Y, location[1]);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_WIDTH, width);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_HEIGHT, height);
        context.startActivity(intent);
    }


    /**
     * 跳转 查看大图 （查看的是用户头像）
     *
     * @param context
     * @param urls            图片url集合
     * @param currentPosition 跳转目标position
     * @param view            控件点击的view
     * @param isHeadPic       查看的是用户头像
     */
    public static void showImageBrowser(Activity context, List<String> urls, int currentPosition, View view, boolean isHeadPic)
    {
        Intent intent = new Intent(context, CommonImageViewAct.class);
        intent.putStringArrayListExtra(CommonConstant.EAM_SHOW_IMG_URLS, (ArrayList<String>) urls);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_CURRENT_ITEM, currentPosition);
        int[] location = new int[2];
        int width = 50;
        int height = 50;
        if (view == null)
        {
            location[0] = CommonUtils.getScreenWidth(context) / 2;
            location[1] = CommonUtils.getScreenHeight(context) / 2;
        }
        else
        {
            view.getLocationOnScreen(location);
            width = view.getWidth();
            height = view.getHeight();
        }
//        location[0] = CommonUtils.getScreenWidth(context) / 2;
//        location[1] = CommonUtils.getScreenHeight(context) / 2;
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_LOCATION_X, location[0]);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_LOCATION_Y, location[1]);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_WIDTH, width);
        intent.putExtra(CommonConstant.EAM_SHOW_IMG_HEIGHT, height);

        intent.putExtra(CommonConstant.EAM_SHOW_IMG_HEAD_PIC, isHeadPic);
        context.startActivity(intent);
       // context.overridePendingTransition(R.anim.no, R.anim.no);
    }


    /**
     * 获取根目录
     *
     * @param context
     * @return
     */
    public static String getRootDirPath(@Nullable Context context)
    {
        if (context == null)
            context = AppController.getInstance();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
            return Environment.getExternalStorageDirectory().getPath() + File.separator +
                    "WaiPai/";
        else
            return context.getFilesDir().getPath() + File.separator + "WaiPai/";
    }

    /**
     * 字符串MD5加密
     *
     * @param s
     * @return
     */
    public static String toMD5(String s)
    {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try
        {
            byte[] btInput = s.getBytes("utf-8");
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取当前应用的版本号
     *
     * @param context
     * @return
     */
    public static int getVerCode(Context context)
    {
        int verCode = -1;
        try
        {
            verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e)
        {
        }
        return verCode;
    }

    /**
     * 获取当前应用的版本名称
     */
    public static String getVerName(Context context)
    {
        try
        {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e)
        {
        }
        return "";
    }

    public static void setAcitivtyAlpha(Activity activity, float alpha)
    {
        Window window = activity.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        wl.alpha = alpha;
        window.setAttributes(wl);
    }

    public static void setTransparentTopBar(Activity act)
    {
        act.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window window = act.getWindow();
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    public static File saveBitmap(Bitmap bitmap, int quality, String filePath, int angle)
    {
        Bitmap rotatedBitmap;
        FileOutputStream out = null;
        ByteArrayOutputStream stream = null;
        if (angle != 0)
        {
            //旋转图片 动作
            Matrix matrix = new Matrix();
            matrix.postRotate(angle);
            rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } else
        {
            rotatedBitmap = bitmap;
        }

        File file = new File(filePath);
        if (file.exists())
        {
            file.delete();
        }
        try
        {
            stream = new ByteArrayOutputStream();
            rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
            out = new FileOutputStream(filePath);
            out.write(stream.toByteArray());

        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                stream.close();
                out.flush();
                out.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

        }
        return file;
    }

    /**
     * sp转px
     *
     * @param context
     * @param sp
     * @return
     */
    public static int sp2px(Context context, int sp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                sp,
                context.getResources().getDisplayMetrics());
    }


    /**
     * 6.0以下的系统检测权限
     *
     * @return
     */
    public static boolean cameraIsCanUse()
    {
        boolean isCanUse = true;
        Camera mCamera = null;
        try
        {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (RuntimeException e)
        {
            Logger.t(TAG).d("相机catch" + e.getMessage());
            e.printStackTrace();
            isCanUse = false;
        }

        if (mCamera != null)
        {
            try
            {
                mCamera.release();
            } catch (Exception e)
            {
                Logger.t(TAG).d("相机catch" + e.getMessage());
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    /**
     * 输入验证
     *
     * @param verifyType 1=密码，2=邮箱，3=电话号码，4=qq号 5:汉字姓名 6:15位身份证号 7:18位身份证号
     * @param inputStr   要验证的输入值
     * @return
     */
    public static boolean verifyInput(int verifyType, String inputStr)
    {
        String rexStr = "";
        switch (verifyType)
        {
            case 1:
                //以字母开头，长度在8~16之间，只能包含字母、数字
                rexStr = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
                break;
            case 2:
                //邮箱
                rexStr = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
                break;
            case 3:
                //rexStr="^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";
                rexStr = "^1\\d{10}$";
                break;
            case 4:
                rexStr = "^\\d{5,15}$";
                break;
            case 5:
                rexStr = "[\\u4e00-\\u9fa5]+";
                break;
            case 6:
                rexStr = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
                break;
            case 7:
                rexStr = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|[Xx])$";
                break;
            default:
                break;
        }
        Pattern password = Pattern.compile(rexStr);
        Matcher m1 = password.matcher(inputStr);
        return m1.matches();
    }


    /**
     * 从Activity跳转登录
     */
    public static void startLoginFromActivity(Activity activity,String requestSource)
    {
        Intent intent = new Intent(activity, LoginAct.class);
        intent.putExtra(CommonConstant.REQUEST_LOGIN_CODE,requestSource);
        activity.startActivityForResult(intent, CommonConstant.REQUEST_CODE_LOGIN);
        activity.overridePendingTransition(R.anim.out_to_bottom, R.anim.no);
    }


    /**
     * 从Fragment跳转登录
     */
    public static void startLoginFromFragment(Fragment fragment,String requestSource)
    {
        Intent intent = new Intent(fragment.getContext(), LoginAct.class);
        intent.putExtra(CommonConstant.REQUEST_LOGIN_CODE,requestSource);
        fragment.startActivityForResult(intent, CommonConstant.REQUEST_CODE_LOGIN);
    }

    public static boolean checkUserStateFromActivity(Activity activity,String requestSource)
    {
        if(isFastDoubleClick())
        {
            return false;
        }

        if (TextUtils.isEmpty(SharePreUtils.getUId())||TextUtils.isEmpty(SharePreUtils.getToken()))
        {
            startLoginFromActivity(activity,requestSource);
            return false;
        }else
            return true;
    }

    public static boolean checkUserStateFromFragment(Fragment fragment,String requestSource)
    {

        if(isFastDoubleClick())
        {
            return false;
        }

        if (TextUtils.isEmpty(SharePreUtils.getUId())||TextUtils.isEmpty(SharePreUtils.getToken()))
        {
            startLoginFromFragment(fragment,requestSource);
            return false;
        }else
            return true;
    }


    /**
     * 分享到微信,微信朋友圈,QQ,QQ空间，看脸好友，新浪微博
     *
     * @param mContext
     * @param shareKey  对应渠道的参数类：微信为 Wechat.ShareParams，微信朋友圈为：WechatMoments.ShareParams等
     * @param shareInfo shareInfo中封装着分享需要的参数
     */
    public static void shareWithApp(final Context mContext, String shareKey, ShareToFaceBean shareInfo)
    {
        //初始化ShareSDK
//        MobSDK.init(mContext);
        PlatformActionListener listener;
        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);//用于微信朋友圈分享检查微信客户端
        Platform qqChat = ShareSDK.getPlatform(QQ.NAME);
        if (shareInfo.getShareListener() == null)
        {
            listener = new PlatformActionListener()
            {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap)
                {
                    Logger.t(TAG).d("分享成功");
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable)
                {
                    Logger.t(TAG).d("分享失败");

                }

                @Override
                public void onCancel(Platform platform, int i)
                {
                    Logger.t(TAG).d("分享取消");
                }
            };
            shareInfo.setShareListener(listener);
        }
        switch (shareKey)
        {
            case "我的动态":

                break;
            case "微信好友":
                if (weChat.isClientValid())
                {
                    Wechat.ShareParams sp = new Wechat.ShareParams();
                    sp.setShareType(shareInfo.getShareType());
                    sp.setTitle(shareInfo.getShareTitle());
                    sp.setUrl(shareInfo.getShareUrl());
                    sp.setText(shareInfo.getShareContent());
                    if (!TextUtils.isEmpty(shareInfo.getShareImgUrl()))
                        sp.setImageUrl(shareInfo.getShareImgUrl());
                    else
                        sp.setImageData(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));
                    weChat.setPlatformActionListener(shareInfo.getShareListener());
                    weChat.share(sp);
                }
                else
                    ToastUtils.showShort("您未安装微信客户端，请先安装");
                break;
            case "QQ好友":
                Logger.t(TAG).d("ShareBean:" + shareInfo.toString());
                if (qqChat.isClientValid())
                {
                    QQ.ShareParams qq = new QQ.ShareParams();
                    qq.setTitle(shareInfo.getShareTitle());
                    qq.setTitleUrl(shareInfo.getShareUrl());
                    qq.setImageUrl(shareInfo.getShareAppImageUrl());
                    qq.setText(shareInfo.getShareContent());
                    qqChat.setPlatformActionListener(shareInfo.getShareListener());
                    qqChat.share(qq);
                }
                else
                    ToastUtils.showShort("您未安装QQ客户端，请先安装");
                break;
//            case "看脸好友":
//                int i = NetHelper.getNetworkStatus(mContext);
//                if (i == -1)
//                {
//                    ToastUtils.showShort("当前无网络连接，请稍后再试！");
//                    return;
//                }
//                String shareTitle, shareContent;
//                Intent intent = new Intent(mContext, RelationAct.class);
//                intent.putExtra("openSource", "share");
//                intent.putExtra("shareType", shareInfo.getOpenSouse());
//                intent.putExtra("sendType", shareInfo.getSendType());
//                if ("liveShare".equals(shareInfo.getOpenSouse()))
//                {
//                    shareTitle = String.format("<html><body><b>#%s#</b>%s</body></html>", shareInfo.getRoomName(), "的直播间");
//                    shareContent = String.format("<html><body>越帅越优惠, 越靓越实惠, 尽在看脸吃饭。点击进入<b>#%s#</b>%s</body></html>", shareInfo.getRoomName(), "的直播间");
//                }
//                else
//                {
//                    shareTitle = shareInfo.getShareTitle();
//                    shareContent = shareInfo.getShareContent();
//                }
//                intent.putExtra("shareTitle", shareTitle);
//                intent.putExtra("shareContent", shareContent);
//                intent.putExtra("shareImageUrl", shareInfo.getShareImgUrl());
//                intent.putExtra("shareUrl", shareInfo.getShareUrl());
//                intent.putExtra("gameId", shareInfo.getGameId());
//                intent.putExtra("roomId", shareInfo.getRoomId());
//                intent.putExtra("columnId", shareInfo.getColumnId());
//                intent.putExtra("activityId", shareInfo.getActivityId());
//                intent.putExtra("nickName", shareInfo.getRoomName());
//                intent.putExtra("messageDes", shareInfo.getMessageDes());
//                intent.putExtra("roomName", shareInfo.getRoomName() + "的直播间");
//                intent.putExtra("clubId", shareInfo.getClubId());
//                ((Activity) mContext).startActivityForResult(intent, EamConstant.EAM_OPEN_RELATION);
//                // mContext.startActivityForResult(intent, EamConstant.EAM_LIVE_SHARED_OPEN_SOURCE);
//                break;
            case "微信朋友圈":
                Platform weChatMoments = ShareSDK.getPlatform(WechatMoments.NAME);
                if (weChat.isClientValid())
                {
                    WechatMoments.ShareParams shareParams = new WechatMoments.ShareParams();
                    shareParams.setShareType(shareInfo.getShareType());
                    shareParams.setTitle(shareInfo.getShareWeChatMomentsTitle());
                    shareParams.setUrl(shareInfo.getShareUrl());
                    shareParams.setText(shareInfo.getShareContent());
                    if (!TextUtils.isEmpty(shareInfo.getShareImgUrl()))
                        shareParams.setImageUrl(shareInfo.getShareImgUrl());
                    else
                        shareParams.setImageData(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));
                    weChatMoments.setPlatformActionListener(shareInfo.getShareListener());
                    weChatMoments.share(shareParams);
                }
                else
                {
                    ToastUtils.showShort("您未安装微信客户端，请先安装");
                }
                break;
            case "QQ空间":
                if (qqChat.isClientValid())
                {
                    Platform qqzone = ShareSDK.getPlatform(QZone.NAME);
                    QZone.ShareParams qz = new QZone.ShareParams();
//                qz.setShareType(shareInfo.getShareType());
//                qz.setUrl(shareInfo.getShareUrl());
                    qz.setSite(shareInfo.getShareSite());
                    qz.setSiteUrl(shareInfo.getShareSiteUrl());
                    qz.setTitle(shareInfo.getShareTitle());
                    qz.setTitleUrl(shareInfo.getShareTitleUrl());
                    qz.setImageUrl(shareInfo.getShareAppImageUrl());
                    qz.setText(shareInfo.getShareContent());

                    qqzone.setPlatformActionListener(shareInfo.getShareListener());
                    // 执行图文分享
                    qqzone.share(qz);
                }
                else
                    ToastUtils.showShort("您未安装QQ客户端，请先安装");

                break;
            case "新浪微博":
                Platform sinaWeibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                if (sinaWeibo.isClientValid())
                {
                    SinaWeibo.ShareParams sinaShareParams = new SinaWeibo.ShareParams();
                    sinaShareParams.setText(shareInfo.getShareSinaContent());
                    if (TextUtils.isEmpty(shareInfo.getShareAppImageUrl()))
                        sinaShareParams.setImageData(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));
                    else
                        sinaShareParams.setImageUrl(shareInfo.getShareAppImageUrl());
                    if (sinaWeibo.isAuthValid())
                    {
                        sinaWeibo.removeAccount(true);
                        ShareSDK.removeCookieOnAuthorize(true);
                    }
                    // 执行图文分享
                    sinaWeibo.setPlatformActionListener(shareInfo.getShareListener());
                    sinaWeibo.share(sinaShareParams);
                }
                else
                    ToastUtils.showShort("您未安装新浪微博客户端，请先安装");
                break;
            default:
                break;
        }
    }

    /**
     * 获取指定文件大小
     * @return
     * @throws Exception 　　
     */
    public static long getFileSize(File file) {
        try
        {
            long size = 0;
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } else {
                file.createNewFile();
            }
            return size;
        } catch (IOException e)
        {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 向相册插入图片 视频
     * @param context
     * @param isVideo
     * @param filePath
     * @param createTime
     */
    public static void insertIntoMediaStore(Context context, boolean isVideo, String filePath, long createTime)
    {
        File saveFile = new File(filePath);
        ContentResolver mContentResolver = context.getContentResolver();
        if (createTime == 0)
            createTime = System.currentTimeMillis();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.TITLE, saveFile.getName());
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, saveFile.getName());
        if (isVideo)
        values.put(MediaStore.Video.Media.DURATION, VideoUtils.getDuration(filePath));
        //值一样，但是还是用常量区分对待
        values.put(isVideo
                ? MediaStore.Video.VideoColumns.DATE_TAKEN
                : MediaStore.Images.ImageColumns.DATE_TAKEN, createTime);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, System.currentTimeMillis());
        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
        if (!isVideo)
            values.put(MediaStore.Images.ImageColumns.ORIENTATION, 0);
        values.put(MediaStore.MediaColumns.DATA, saveFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.SIZE, saveFile.length());
        values.put(MediaStore.MediaColumns.MIME_TYPE, isVideo ? "video/3gp" : "image/jpeg");
        //插入
        mContentResolver.insert(isVideo
                ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                : MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(filePath)));
    }

    /**
     * 获取图片旋转角度
     * @param filepath
     * @return
     */
    public static int getExifOrientation(String filepath) {
        int degree = 0;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {
            Log.d(TAG, "cannot read exif" + ex);
        }
        if (exif != null) {
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            if (orientation != -1) {
                switch(orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
            }
        }
        return degree;
    }

    /**
     * 旋转图片
     * @param angle 被旋转角度
     * @return 旋转后的图片
     */
    public static String rotaingImageView(int angle, String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        File file = new File(path);
        if (file.exists())
            file.delete();
        FileOutputStream outStream = null;
        String fileName = path;
        try {
            outStream = new FileOutputStream(fileName);
            // 把数据写入文件，100表示不压缩
            returnBm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (outStream != null) {
                    // 记得要关闭流！
                    outStream.close();
                }
                if (returnBm != null) {
                    returnBm.recycle();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static long lastClickTime;

    /**
     * 是否重复点击
     *
     * @return true 是，false 否
     */
    public static boolean isFastDoubleClick()
    {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 800)
        {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 把文件拷贝到某一目录下
     * @param srcFile
     * @param destDir
     * @return
     */
    public static boolean copyFileToDir(String srcFile, String destDir){
        File fileDir = new File(destDir);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String destFile = destDir +"/" + new File(srcFile).getName();
        try{
            InputStream streamFrom = new FileInputStream(srcFile);
            OutputStream streamTo = new FileOutputStream(destFile);
            byte buffer[]=new byte[1024];
            int len;
            while ((len= streamFrom.read(buffer)) > 0){
                streamTo.write(buffer, 0, len);
            }
            streamFrom.close();
            streamTo.close();
            return true;
        } catch(Exception ex){
            return false;
        }
    }


    /**
     * 移动文件到某一路径下
     * @param srcFile
     * @param destDir
     * @return
     */
    public static boolean moveFile(String srcFile, String destDir) {
        //复制后删除原目录
        if (copyFileToDir(srcFile, destDir)) {
            File file = new File(srcFile);
            if (file.exists())
            {
                return file.delete();
            }
        }
        return false;
    }

    public synchronized static boolean isVoicePermission()
    {
        try
        {
            AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, 22050, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, AudioRecord.getMinBufferSize(22050, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT));
            record.startRecording();
            int recordingState = record.getRecordingState();
            if (recordingState == AudioRecord.RECORDSTATE_STOPPED)
            {
                record.release();
                return false;
            }
            record.release();
            return true;
        } catch (Exception e)
        {
            return false;
        }
    }


    /**
     * 获取安装 App(支持 8.0)的意图
     * <p>8.0 需添加权限
     * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p>
     *
     * @param file      文件
     * @param authority 7.0 及以上安装需要传入清单文件中的{@code <provider>}的 authorities 属性
     *                  <br>参看 https://developer.android.com/reference/android/support/v4/content/FileProvider.html
     * @param isNewTask 是否开启新的任务栈
     * @return 安装 App(支持 8.0)的意图
     */
    public static Intent getInstallAppIntent(final File file, final String authority, final boolean isNewTask)
    {
        if (file == null) return null;
        Intent intent = new Intent(Intent.ACTION_VIEW);//I3CKBE  LHUW8P
        Uri data;
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
        {
            data = Uri.fromFile(file);
        }
        else
        {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            data = FileProvider.getUriForFile(AppController.getInstance(), authority, file);
        }
        intent.setDataAndType(data, type);
        return getIntent(intent, isNewTask);
    }
    private static Intent getIntent(final Intent intent, final boolean isNewTask)
    {
        return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent;
    }
}